package io.wdb.modules.activity.wxapp.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.wdb.exchange.model.User;
import com.wdb.exchange.model.WxUserRelationRpcModel;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.wdb.common.exception.RspCodeEnum;
import io.wdb.common.utils.CommonUtil;
import io.wdb.common.utils.UUIDGenerator;
import io.wdb.handler.ApiServiceHandler;
import io.wdb.modules.activity.wxapp.dao.HdUserDao;
import io.wdb.modules.activity.wxapp.entity.HdReadActivityRankEntity;
import io.wdb.modules.activity.wxapp.entity.HdUserEntity;
import io.wdb.modules.activity.wxapp.entity.HdUserRankEntity;
import io.wdb.modules.activity.wxapp.service.HdUserService;



@Service("hdUserService")
public class HdUserServiceImpl implements HdUserService {
	private static final Logger logger = LoggerFactory.getLogger(HdUserServiceImpl.class);
	@Autowired
	private HdUserDao hdUserDao;
	
	@Autowired
	private ApiServiceHandler apiServiceHandler;
	
	@Override
	public HdUserEntity queryObject(String id){
		return hdUserDao.queryObject(id);
	}
	
	@Override
	public List<HdUserEntity> queryList(Map<String, Object> map){
		return hdUserDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return hdUserDao.queryTotal(map);
	}
	
	@Override
	public synchronized String save(HdUserEntity hdUser) {
		Map<String, Object> map = new HashMap<String, Object>();
		if("null".equals(hdUser.getUnionid())){
			hdUser.setUnionid(null);
		}
		if(hdUser.getWxAppid() != null && hdUser.getWxOpenid() != null) {
			map.put("wxAppid", hdUser.getWxAppid());
			map.put("wxOpenid", hdUser.getWxOpenid());
		}else {
			map.put("unionid", hdUser.getUnionid());
		}

		List<HdUserEntity> entities = hdUserDao.queryList(map);
		if (entities != null && entities.size() > 0) {// 存在则更新
			hdUser.setId(entities.get(0).getId());
			hdUserDao.update(hdUser);
		} else {// 不存在则新增
			synchronized (hdUser) {
				if (ObjectUtils.isEmpty(hdUser.getCreateTime())) {
					hdUser.setCreateTime(new Date());
				}
				hdUser.setId(UUIDGenerator.getUUID());
				hdUserDao.save(hdUser);
			}

		}

		return hdUser.getId();

	}
	
	@Override
	public void update(HdUserEntity hdUser){
		hdUserDao.update(hdUser);
	}
	
	@Override
	public void updateByUnionid(HdUserEntity hdUser){
		if(hdUser.getUnionid() != null) {
			Map<String, Object> map = new HashMap<>();
			map.put("unionid", hdUser.getUnionid());
			map.put("wxOpenid", hdUser.getWxOpenid());
			List<HdUserEntity> users =  hdUserDao.queryList(map);
			if(users != null  && users.size() > 0) {
				hdUserDao.updateByUnionid(hdUser);
			}else {
				save(hdUser);
			}
		}
		
	}
	
	@Override
	public void delete(String id){
		hdUserDao.delete(id);
	}
	
	@Override
	public void deleteBatch(String[] ids){
		hdUserDao.deleteBatch(ids);
	}

	@Override
	public Map<String, Object> queryReadingList(Map<String, Object> map) {
		//查询周排名
		Map<String, Object> result = new HashMap<String, Object>();
		
		map.put("sortType", 0);
		List<HdUserRankEntity> list = hdUserDao.queryReadingList(map);
		
		HdUserRankEntity rankEntity = hdUserDao.queryUserReadRank(map);
		
		HdReadActivityRankEntity weekData = new HdReadActivityRankEntity();
		weekData.setList(list);
		weekData.setRead_count(rankEntity.getReadCount());
		weekData.setUserRank(rankEntity.getRank());
		result.put("weekData", weekData);
		//查询月排名
		map.put("sortType", 1);
		List<HdUserRankEntity> monthList = hdUserDao.queryReadingList(map);
		
		HdUserRankEntity monthRankEntity = hdUserDao.queryUserReadRank(map);
		
		HdReadActivityRankEntity monthData = new HdReadActivityRankEntity();
		monthData.setList(monthList);
		monthData.setRead_count(monthRankEntity.getReadCount());
		monthData.setUserRank(monthRankEntity.getRank());
		result.put("monthData", monthRankEntity);
		//查询总排名
		map.put("sortType", 2);
		List<HdUserRankEntity> totalList = hdUserDao.queryReadingList(map);
		
		HdUserRankEntity totalRankEntity = hdUserDao.queryUserReadRank(map);
		
		HdReadActivityRankEntity totalData = new HdReadActivityRankEntity();
		totalData.setList(totalList);
		totalData.setRead_count(totalRankEntity.getReadCount());
		totalData.setUserRank(totalRankEntity.getRank());
		result.put("totalData", totalRankEntity);
		return result;
	}

	/**
	 * 根据群内unionid查询对应的群数据
	 */
	@Override
	public List<HdUserRankEntity> queryWeekReadingList(Map<String, Object> map) {
		List<HdUserRankEntity> entities = hdUserDao.queryWeekReadingList(map);
		return entities;
	}
	
	/**
	 * 根据usertoken查询userinfo信息
	 */
	public synchronized HdUserEntity getUserinfoByUsertoken(String apiUrl, String appid,String userid,String usertoken, String mobile) {
		if(ObjectUtils.isEmpty(userid) || "undentified".equals(userid)) {
			userid = null;
		}
		if(ObjectUtils.isEmpty(mobile) || "undentified".equals(mobile)) {
			mobile = null;
		}
		//===========RPC 获取用户信息
		HdUserEntity hdUserEntity = null;
		if(CommonUtil.isEmpty(usertoken)) {
			return hdUserEntity;
		}
		try {
		 User user = apiServiceHandler.getWxUserinfoByToken(usertoken, userid, appid);
		 if(RspCodeEnum.CODE_SUCCESS.getRspCode() == user.code) {
			 //接口返回成功，处理业务逻辑
			 if(!CommonUtil.isEmpty(user.detail)) {
					if (!CommonUtil.isEmpty(user.detail.get("wxUserRelation"))) {
						WxUserRelationRpcModel wxUserRelationJson = (WxUserRelationRpcModel) user.detail.get("wxUserRelation");

						if (!CommonUtil.isEmpty(wxUserRelationJson.getOpenid())) {
							hdUserEntity = new HdUserEntity();
							hdUserEntity.setMobile(wxUserRelationJson.getMobile());
							hdUserEntity.setAvatar(wxUserRelationJson.getAvatarUrl());
							hdUserEntity.setNickname(wxUserRelationJson.getNickName());
							hdUserEntity.setUnionid(wxUserRelationJson.getUnionid());
							hdUserEntity.setWxOpenid(wxUserRelationJson.getOpenid());
							hdUserEntity.setWxAppid(wxUserRelationJson.getAppId());
							hdUserEntity.setSessionKey(wxUserRelationJson.getSessionKey());
							if (!ObjectUtils.isEmpty(userid)) {
								hdUserEntity.setApiUserId(Long.valueOf(userid));
							} else if (!CommonUtil.isEmpty(wxUserRelationJson.getUserId())) {
								hdUserEntity.setApiUserId(wxUserRelationJson.getUserId());
							}
							hdUserEntity.setNewUser(wxUserRelationJson.getNewUser());
							hdUserEntity.setId(save(hdUserEntity));// 保存hdUserEntity信息
						}
					}
			 }
		 }
		 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hdUserEntity;
		
	}
}
